﻿package net.wangit.adm.admin;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.support.action.DefaultAction;
import net.wangit.user.admin.AdminCache;


public class SaveAdminAction extends DefaultAction {

	private static final String ORGANIZATION_UPDATE = "update AADMINORG set adminid=? where adminid=?";
	private static final String GROUP_UPDATE = "update AADMINGROUP set adminid=? where adminid=?";
	private static final String ROLE_UPDATE = "update AADMINROLE set adminid=? where adminid=?";
	private static final String USER_UPDATE = "update AUSER set adminid=? where adminid=?";

	public SaveAdminAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		super.doAction(db, ac);
		List<Table> tables = ac.getTables();
		Table table = tables.get(0);
		List<ColumnRow> rows = table.getRows();
		for (int i = 0; i < rows.size(); i++) {
			ColumnRow row = rows.get(i);
			if (row.isUpdateRow()) {
				update(db, row.get("adminid"), row.getPrimaryKey("adminid"));
			}
		}

		AdminCache.clearAll();
	}

	private void update(DB db, String newId, String oldId) throws Exception {
		if (!oldId.equals(newId)) {
			String values[] = { newId, oldId };
			int types[] = { 2, 2 };
			db.execute(SaveAdminAction.ORGANIZATION_UPDATE, values, types);
			db.execute(SaveAdminAction.ROLE_UPDATE, values, types);
			db.execute(SaveAdminAction.GROUP_UPDATE, values, types);
			db.execute(SaveAdminAction.USER_UPDATE, values, types);
		}
	}
}
